<template>
    <el-dialog :title="form.id?'修改目录':'新增目录'" :visible="showDialog" width="40%" @close="closeFn" @open="openFn">
      <el-form :model="form" label-width="80px" :rules="rules" ref="form">
        <el-form-item label="所属学科" prop="subname" v-if="!$route.query.id">
          <el-select v-model="form.subname" @focus="focus">
            <el-option v-for="item in subjectList" :key="item.id" :value="item.id" :label="item.subjectName">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="目录名称" prop="directoryName">
          <el-input v-model="form.directoryName"></el-input>
        </el-form-item>
      </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button @click="closeFn">取 消</el-button>
      <el-button type="primary" @click="addFn">确 定</el-button>
    </div>
  </el-dialog>

</template>

<script>
import { list as subList } from '@/api/hmmm/subjects'
import { add, detail, update } from '@/api/hmmm/directorys'
export default {
  name: 'AddDirectorys',
  props: {
    showDialog: {
      type: Boolean,
      default: false
    },
    row: {
      type: Object,
      required: true
    }
  },
  data () {
    return {
      subjectList: [],
      form: {
        subname: '',
        directoryName: ''
      },
      rules: {
        subname: [
          { required: true, message: '所属学科不得为空' }
        ],
        directoryName: [
          { required: true, message: '目录名称不得为空' }
        ]
      }
    }
  },
  methods: {
    closeFn () {
      this.form = {
        subname: '',
        directoryName: ''
      }
      this.$refs.form.resetFields()
      this.$emit('closeDialog')
    },
    async addFn () {
      try {
        await this.$refs.form.validate()
      } catch {
        return
      }
      if (this.form.id) {
        await update({
          id: this.row.id,
          subjectID: this.row.subjectID,
          directoryName: this.form.directoryName
        })
      } else {
        await add({
          subjectID: this.form.subname,
          directoryName: this.form.directoryName
        })
      }
      this.$message.success('操作成功')
      this.$emit('getRender')
      this.$emit('closeDialog')
    },
    async focus () {
      const res = await subList()
      this.subjectList = res.data.items
    },
    async showDetail () {
      const res = await detail({
        id: this.row.id
      })
      this.form = { ...res.data, subname: this.row.subjectName }
    },
    openFn () {
      if (this.row.id) {
        this.showDetail()
      }
    }

  }
}
</script>

<style scoped lang='less'></style>
